<template>
  <el-select
    v-model="selectValue"
    placeholder="Select"
    size="large"
    clearable
    filterable
    style="width: 100%"
    @change="change"
  >
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />

    <div style="padding: 10px">
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :total="routeTotal"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handlePageSizeChange"
        @current-change="handlePageNumChange"
      />
    </div>
  </el-select>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
// import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import { getRoutesListApi } from '@/request/api/routes'
import { useMessageAlertStore } from '@/features/store/componentStore'

const props = defineProps({
  selectValue: { type: String, default: '' },
  // 路由分类id，包含所有上级分类id
  queryRouteSortId: { type: Array as () => string[], default: [] },
})

const emit = defineEmits(['selectValueChange'])
// 下拉框值的变化
const change = (val: any) => emit('selectValueChange', val)

const { openAlert } = useMessageAlertStore()

onMounted(() => {
  getRoutesList(props.queryRouteSortId)
  selectValue.value = props.selectValue
})

watch(
  () => props.queryRouteSortId,
  () => getRoutesList(props.queryRouteSortId)
)

const routeTotal = ref<number>(0)
const pageNum = ref<number>(1)
const pageSize = ref<number>(20)
const handlePageNumChange = (val: number) => {
  pageNum.value = val
  getRoutesList(props.queryRouteSortId)
}
const handlePageSizeChange = (val: number) => {
  pageSize.value = val
  getRoutesList(props.queryRouteSortId)
}

// 下拉框选项
const options = ref<{ value: string; label: string }[]>([])
// 下拉框选择的值
const selectValue = ref<string>('')

// 获取路由列表
const getRoutesList = async (sortIdList: string[]) => {
  let sortId = ''
  if (sortIdList && sortIdList.length > 0)
    sortId = sortIdList[sortIdList.length - 1]

  const res = await getRoutesListApi(pageNum.value, pageSize.value, sortId)
  if (res.code !== 200) return openAlert.error(res.message)
  // ElMessage.success('查询分类下的路由列表成功')

  let temp = []
  res.data.records.forEach((item: any) => {
    temp.push({ value: item.id, label: item.path })
  })
  options.value = temp
  routeTotal.value = res.data.total
}
</script>

<style lang="less" scoped>
.label {
  font-size: 16px;
  font-weight: bold;
  color: #606266;
  padding: 10px 20px;
  user-select: none;
}
</style>
